/**
 *  提交订单模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	require("../../custom/base/component-core.js");
		
	require("../../custom/base/component-md5.js");
	
	var validate = require("../../custom/base/component-validate.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
		
	var async = require("../../custom/base/component-async.js");
	

	var cartIds;
	
	//初始化函数
	exports.init=function(m){
		
		window.$ldh_order=m;
		
		cartIds=base.getParameter("cartIds");
		/*exports.getOrderPayMentType("");
		
	  */
		exports.getMyAddressList();
		
		exports.getOrderGoods(cartIds);
	};
	
	
	//查询订单商品
	exports.getOrderGoods=function(cartId){
		
		base.showLoading();
		
		var params = {
				cartId : cartId,
				userId : base.getCookie("userId"),
				"loginSign":$ldh_base.getCookie("loginSign"),
				"sign":MD5($ldh_base.getCookie("loginSign")+cartId)
				
		};
	
		
		
			eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopapp/Order/getOrderGoods.do", params));
						
					
						if(data["code"]==1){
							
							var htmlStr="";
							
							var index = 0,totalPrice=0,totalMerNum=0; 
							var arr_shop_id = new Array();
							for(var i=0;i<data["data"].length;i++){
								arr_shop_id.push(data["data"][i]["shopId"]);
											htmlStr += '<ul>';
											htmlStr += '<li><p>店铺：'+data["data"][i]["shopName"]+'</p></li>';
											 var price=0,nums=0;
											 for (var j = 0; j < data["data"][i]["goods"].length;j++) {
													htmlStr += '<li class="clearfix" onClick=window.location.href="?merchandiseId='+data["data"][i]["goods"][j]["merchandiseId"]+'#ldhGoods">';
													htmlStr += '<div class="store_goods_pic" ><a data-transition="none" href=""><img src="'+fileOpenUrl+data["data"][i]["goods"][j]["picdefault"]+'"/></a></div>';
													htmlStr += '<div class="store_goods_info">';
													htmlStr += '<h3>'+data["data"][i]["goods"][j]["merchandiseName"]+'</h3>';
													htmlStr += '<strong class="order_info">'+data["data"][i]["goods"][j]["price"]+'元<span>x</span>'+data["data"][i]["goods"][j]["nums"]+'</strong>';
													htmlStr += '</div>';
													htmlStr += '</li>';
													nums=nums+parseInt(data["data"][i]["goods"][j]["nums"]);
													price=price+Number(data["data"][i]["goods"][j]["price"]*data["data"][i]["goods"][j]["nums"]);
													totalMerNum=totalMerNum+parseInt(data["data"][i]["goods"][j]["nums"]);
													totalPrice=totalPrice+Number(data["data"][i]["goods"][j]["price"]*data["data"][i]["goods"][j]["nums"]);
													exports.setAddOrderParams("orderitemslist["+index+"].cartId",data["data"][i]["goods"][j]["cartId"]);
													exports.setAddOrderParams("orderitemslist["+index+"].merchandiseId",data["data"][i]["goods"][j]["merchandiseId"]);
													exports.setAddOrderParams("orderitemslist["+index+"].shopId",data["data"][i]["goods"][j]["shopId"]);
													exports.setAddOrderParams("orderitemslist["+index+"].userId",data["data"][i]["goods"][j]["userId"]);
													exports.setAddOrderParams("orderitemslist["+index+"].nums",data["data"][i]["goods"][j]["nums"]);
													index++;
											 }
											 
											htmlStr += '<li><p class="text-right order_losing"><span>共<strong class="order_num">'+nums+'</strong>件</span><span>合计：<strong class="main_color">'+price.toFixed(2)+'元</strong></span></p></li>';
											htmlStr += '<li><input data-role="none" type="text" class="message_to" placeholder="给商家留言" /></li>';
											htmlStr += '</ul>';
											
							}
							
						exports.getOrderPayMentType(arr_shop_id.join(","))
							
						$("#ldhOrder .orderGoodList").html(htmlStr);
						$("#ldhOrder .order_btm em:eq(0)").html(totalMerNum);
						$("#ldhOrder .order_btm em:eq(1)").html(totalPrice.toFixed(2));
 
						}else if(data["code"]=="-10001"){
							
							alert(data["message"]);
							
						}
						
						
						
		}))().start();
		
	};
	
	//设置送货时间
	exports.setShipTime=function(obj){
		
		var shipTime=$(obj).val();
		this.shipTime=shipTime;
		
	//	$("#ldhOrder .delivery_time em").html(shipTime);	
		
		//base.showDiv("#ldhOrder");;
	};
	
	//获取送货时间
	exports.getShipTime=function(){
		
		return this.shipTime==null?"尽快送达":this.shipTime;
		
	};
	
	
	//设置支付方式
	exports.setPaymentType=function(payment){
		
		this.payment=payment;
		
	};
	
	//获取支付方式
	exports.getPaymentType=function(){
		
		return this.payment==null?"1":this.payment;
		
	};
	
	
	//查询支付方式
	exports.getOrderPayMentType=function(shopids){
		
		var params={
				shopids:shopids,
				userId: base.getCookie("userId"),
				"loginSign":$ldh_base.getCookie("loginSign"),
				"sign":MD5($ldh_base.getCookie("loginSign")+base.getCookie("userId")+shopids)
			};

		eval(Wind.compile("async", function() {

			var data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopapp/Order/getOrderPayMentType.do", params));

			if(data.code == "1"){
				var htmlStr="";
				for (var i = 0; i < data["list"].length; i++) {
					var chk = "",on=""; 
					if(data["list"][i].PAYMENT_ID=="1" || data["list"].length==1){
						chk='checked="checked"';
						on="on"
						exports.setPaymentType(data["list"][i].PAYMENT_ID);
					}
		            htmlStr += '<span class="payment '+on+'" onclick=$ldh_order.setPaymentType("'+data["list"][i].PAYMENT_ID+'")><input '+chk+' data-role="none" type="radio" name="payment" class="opacity_0" value="'+data["list"][i].PAYMENT_ID+'"/><em>'+data["list"][i].PAYMENT_NAME+'</em></span>';
				}
                 
                 $("#ldhOrder .paymentType").html('<span>支付方式：</span>'+htmlStr);
			}else{
				
			}
			
			base.cancelLoading();
			
		}))().start();
		
	};
	
	//查询收货地址列表
	exports.getMyAddressList=function(){
				
		var params={
				userId:$ldh_base.getCookie("userId"),
				currentPage:1,
				pageSize:10,
				loginSign:$ldh_base.getCookie("loginSign"),
				sign:MD5($ldh_base.getCookie("loginSign")+$ldh_base.getCookie("userId")+10+""+1)
			};

		eval(Wind.compile("async", function() {

			var data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopapp/Address/addressList.do", params));

			if(data.code == "1"){
				
				var htmlStr="";
				
				for(var i=0;i<data["addressList"].length;i++){
					if(data["addressList"][i]["def"]=="1"){
						//htmlStr += '<a data-transition="none" href=javascript:window.location.href="?fromPage=suborder&cartIds='+cartIds+'#ldhMyAdress">';
						htmlStr += '<a data-transition="none" href=javascript:window.location.href="'+ctx+'/h5/address.shtml?fromPage=suborder&cartIds='+cartIds+'">';
						htmlStr += '<h3><span>'+data["addressList"][i]["shipName"]+'</span><span>'+data["addressList"][i]["shipMobile"]+'</span></h3>';
						htmlStr += '<p>'+data["addressList"][i]["memo"]+'</p></a>';
						exports.setAddressId(data["addressList"][i]["addressId"]);
					}
			     }
			
				if(validate.isNull(htmlStr)){
					htmlStr += '<a data-transition="none" href="">';
					//htmlStr += '<h3 onclick=window.location.href="?fromPage=suborder&cartIds='+cartIds+'#ldhNewAdress"><span>收货地址不能为空,请先添加收货地址</span></h3></a>';
					htmlStr += '<h3 onclick=window.location.href="'+ctx+'/h5/address.shtml?fromPage=suborder&cartIds='+cartIds+'"><span>收货地址不能为空,请先添加收货地址</span></h3></a>';
				}
				
				$("#ldhOrder .order_top").html(htmlStr);
				
			
			}else{
				
			}
		}))().start();
		
	};
	//打开添加收货地址
	exports.openEditAddress=function(type){
		
		if(type=="1"){
			
			$(".ldh-myAdress-edit").show();	
			
			exports.findAllProvince();
			
		}else{
			

			if($(".ldh-myAdress-edit").is(":visible")){
				
				$(".ldh-myAdress-edit").hide();	
				
			}else{
				
				$(".ldh-myAdress-edit").show();	
				
				exports.findAllProvince();
			}
			
		}
		
		
		
	
		
	};
	
	//保存收货地址
	exports.saveAddress=function(type){
		
		var provinceId=exports.getProvinceId();
		var cityId=exports.getCityId();
		var regionId=exports.getRegionId();
		var ship_address=$("#order_ship_address").val();
		var ship_mobile=$("#order_ship_mobile").val();
		var shipName=$("#order_shipName").val();
		
		$("#div_address_tip").show();
		
		if(validate.isNull(shipName)){
		   $("#div_address_tip span").html("收货人不能为空");
		   return;
		}
		if(validate.isNull(provinceId)){
			$("#div_address_tip span").html("请选择省份");
		   return;
		}
		if(validate.isNull(cityId)){
			$("#div_address_tip span").html("请选择城市");
		   return;
		}
		if(validate.isNull(regionId)){
			$("#div_address_tip span").html("请选择区域");
		   return;
		}
		if(validate.isNull(ship_address)){
		   $("#div_address_tip span").html("请填写详细地址");
		   return;
		}
		if(!validate.isMobile(ship_mobile)){
			   $("#div_address_tip span").html("请填写正确的手机号码");
			   return;
			}
		
		var memo=$("#province_name").text()+" "+$("#city_name").text()+" "+$("#region_name").text()+" "+ship_address;
		
		var params={
				"userId":$("#session_userid").val(),
				"provinceId":provinceId,
				"cityId":cityId,
				"regionId":regionId,
				"memo":memo,
				"shipName":shipName,
				"shipMobile":ship_mobile,
				"street":ship_address,
				"def":"1"
			};
		
		if(type=="1"){
			params["addressId"]=exports.getAddressId();
		}

		$("#div_address_tip span").html("正在提交,请稍候...");

		eval(Wind.compile("async", function() {
			var data;
			if(type=="0"){
				
				data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Address/saveAddress.do", params));

			}else{
				
				data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Address/updateAddress.do", params));

			}
			
			$("#div_address_tip").show();
			 
			if(data.code == "1"){
				
				 $(".ldh-myAdress-edit").hide();
				 
				  if(type=="1"){
					  
					 $("#div_address_tip span").html("编辑成功");
					  
					 $(".ldh-myAdress-new button").html("添加新地址");
						
					 $("#btn_edit_address").attr("onclick","$ldh_order.saveAddress(0)");
					 
				  }else{
					  
					  $("#div_address_tip span").html("添加成功");
				  }
				  
					exports.setProvinceId("","请选择");
					exports.setCityId("","请选择");
					exports.setRegionId("","请选择");
					$("#order_ship_address").val("");
					$("#order_ship_mobile").val("");
					$("#order_shipName").val("");
					
				 exports.getMyAddressList();
				
			}else{
				
				
				 $("#div_address_tip span").html(data.message);
			}
			
			task("#div_address_tip").start();
			
			
		}))().start();
		
	};
	
	//删除收货地址
	exports.deleteAddress=function(def,addressId){
		
		/*if(def=="1")
		{
		  alert("不能删除默认收货地址");
		  return;	
		}*/
		
		var params={
			"addressId":addressId
		};
		
		eval(Wind.compile("async", function() {

			var data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Address/delAddress.do", params));
			
			if(data.code == "1"){
				
				$(".ldh-myAdress-edit").hide();	
				
				 $(".ldh-myAdress-new button").html("添加新地址");
					
				 $("#btn_edit_address").attr("onclick","$ldh_order.saveAddress(0)");
				
				 exports.getMyAddressList();
				
			}else{
				
				
			}
			
			
		}))().start();
	};
	
	//加载收货地址,用户编辑
	exports.loadAddress=function(addressId){
		
		exports.setAddressId(addressId);
		
		exports.openEditAddress(1);
		
		$(".ldh-myAdress-new button").html("编辑收货地址");
		
		$("#btn_edit_address").attr("onclick","$ldh_order.saveAddress(1)");
		
		$("#div_address_loading").show();
		
		$("#div_address_tip").hide();
		
		var params={
				"addressId":addressId
			};
			
			eval(Wind.compile("async", function() {

				var data= $await(async.DDF_AsyncRequest("POST",ctx+"/shopweb/Address/loadAddress.do", params));
				
				if(data.code == "1"){
					
					exports.setProvinceId(data["address"]["provinceId"]);
					exports.setCityId(data["address"]["cityId"]);
					exports.setRegionId(data["address"]["regionId"]);
					$("#order_ship_address").val(data["address"]["street"]);
					$("#order_ship_mobile").val(data["address"]["shipMobile"]);
					$("#order_shipName").val(data["address"]["shipName"]);
					$("#province_name").html(data["address"]["provinceName"]);
					$("#city_name").html(data["address"]["cityName"]);
					$("#region_name").html(data["address"]["regionName"]);
					
					
				}else{
					
					
				}
				$("#div_address_loading").hide();
				
			}))().start();
		
	};
	
	/**
	 * 查询所有省份
	 */
	exports.findAllProvince=function(){
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findAllProvince.do", ""));
					
					findAllProvinceCallBack(data);

				}))().start();
		
	};
	
	/**
	 * 查询所有省份_回调函数
	 */
	function findAllProvinceCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
			
			htmlStr+='<li><a href=javascript:$ldh_order.setProvinceId("'+data[i].PROVINCE_ID+'","'+data[i].PROVINCE_NAME+'")>'+data[i].PROVINCE_NAME+'</a></li>';
		}
		
		$("#provinceList").html('<li><a href=javascript:$ldh_order.setProvinceId("","请选择")>请选择</a></li>'+htmlStr);
	}
	
	/**
	 * 根据省份查询城市
	 */
	function findCityByProvince(provinceId){
		
		var params={
			provinceId:provinceId
		};
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findCityByProvince.do",params));
					
					findCityByProvinceCallBack(data);

				}))().start();
	}
	
	/**
	 * 根据省份查询城市
	 */
	function findCityByProvinceCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
						
			htmlStr+='<li><a href=javascript:$ldh_order.setCityId("'+data[i].CITY_ID+'","'+data[i].CITY_NAME+'")>'+data[i].CITY_NAME+'</a></li>';
		}
		
		$("#cityList").html('<li><a href=javascript:$ldh_order.setCityId("","请选择")>请选择</a></li>'+htmlStr);
	}
	
	/**
	 * 根据城市查询区域
	 */
	function findRegionByCity(cityId){
		
		var params={
				cityId:cityId
			};
		
		eval(Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findRegionByCity.do",params));
					
					findRegionByCityCallBack(data);

				}))().start();
	}
	
	/**
	 * 根据城市查询区域_回调函数
	 */
	function findRegionByCityCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
			
			htmlStr+='<li><a href=javascript:$ldh_order.setRegionId("'+data[i].REGION_ID+'","'+data[i].REGION_NAME+'")>'+data[i].REGION_NAME+'</a></li>';

		}
		
		$("#regionList").html('<li><a href=javascript:$ldh_order.setRegionId("","请选择")>请选择</a></li>'+htmlStr);
		
	}
	
	exports.setAddressId=function(addressId){
		
		this.addressId=addressId;
	
	};
	
	exports.getAddressId=function(){
		
		return this.addressId==null?"":this.addressId;
		
	};
	
	exports.setProvinceId=function(provinceId,provinceName){
		
		this.provinceId=provinceId;
		
		$("#province_name").html(provinceName);
		
		$("#provinceList").parent().removeClass("open");
		
		exports.setCityId("","请选择");
		
		exports.setRegionId("","请选择");
		
		if(provinceId=="")
			return;
		
		findCityByProvince(provinceId);
		
	};
	
	exports.getProvinceId=function(){
		
		return this.provinceId==null?"":this.provinceId;
		
	};
	
	exports.setCityId=function(cityId,cityName){
		
		this.cityId=cityId;
		
		$("#city_name").html(cityName);
		
		$("#cityList").parent().removeClass("open");
		
		exports.setRegionId("","请选择");
		
		if(cityId=="")
			return;
		
		findRegionByCity(cityId);
		
	};
	
	exports.getCityId=function(){
		
		return this.cityId==null?"":this.cityId;
		
	};
	
	
	exports.setRegionId=function(regionId,regionName){
		
		this.regionId=regionId;
		
		$("#region_name").html(regionName);
		
		$("#regionList").parent().removeClass("open");
		
		
		if(regionId=="")
			return;
		
	};
	
	exports.getRegionId=function(){
		
		return this.regionId==null?"":this.regionId;
		
	};
	//定时提示信息
	var tips_task = eval(Wind.compile("async", function (divId) {
		
	    $await(Wind.Async.sleep(2000));
	   
	    $(divId).hide();
	    
	    
	}));
	
	var task = eval(Wind.compile("async", function (divId) {
	    $await(tips_task(divId));
	}));
	
	var params={};
	//设置订单参数
	exports.setAddOrderParams=function(key,value){
		
		params[key]=value;
		
	};
	
	//获取订单参数
	exports.getAddOrderParams=function(){
		
		return params==null?"":params;
		
	};
	
	//提交订单
	var clickable=true;
	exports.addOrder=function(obj){
		
		var shipTime=exports.getShipTime();
		
		var addressId=exports.getAddressId();
		
		var paymentId=exports.getPaymentType();
		
				
		if(validate.isNull(addressId)){
			showTips("收货地址不能为空");
			return;
		}
		
		if(!clickable){
			return;
		}
		
		clickable=false;
		
		
		base.showLoading();
		
		//exports.setAddOrderParams("model","H5 "+base.getExplorerInfo().type+" "+base.getExplorerInfo().version);
		
		exports.setAddOrderParams("model","H5");

		exports.setAddOrderParams("terminalId","");
		
		exports.setAddOrderParams("paymentId",paymentId);
		
		exports.setAddOrderParams("addressId",addressId);
		
		exports.setAddOrderParams("shipTime",shipTime);
		
		exports.setAddOrderParams("userId",$ldh_base.getCookie("userId"));
		
		exports.setAddOrderParams("loginSign",$ldh_base.getCookie("loginSign"));

		exports.setAddOrderParams("sign",MD5($ldh_base.getCookie("loginSign")+$ldh_base.getCookie("userId")+addressId+shipTime+paymentId));

		
		for(var i=0;i<$("#ldhOrder .orderGoodList .message_to").length;i++){
			
			 exports.setAddOrderParams("orderMessagelist["+i+"].content",$("#ldhOrder .sorderGoodList .message_to:eq("+i+")").val());
		}
		
		
		eval(Wind.compile("async", function() {

			var data = $await(async.DDF_AsyncRequest("POST", ctx
					+ "/shopapp/Order/addOrder.do",exports.getAddOrderParams()));
			var htmlStr="";
			if(data.code=="1"){
				
				
				
						
				
				if(data["paymentId"]=='1'){
					//货到付款
					for(var i=0;i<data["orderInfos"].length;i++){
						
						htmlStr += '<div class="row">';
						htmlStr += '<ul>';
						htmlStr += '<li>';
						htmlStr += '<p class="order_success">订单提交成功，等待发货</p>';
						htmlStr += '</li>';
						htmlStr += '<li><span>订单编号：</span><span class="orderId">'+data["orderInfos"][i]["orderId"]+'</span></li>';
						htmlStr += '<li><span>店铺名称：</span><span class="shopName">'+data["orderInfos"][i]["shopName"]+'</span></li>';
						htmlStr += '<li><span>应付金额：</span><span class="amount">'+Number(data["orderInfos"][i]["amount"]).toFixed(2)+'元</span></li>';
						htmlStr += '</ul>';
						htmlStr += '</div>';
						htmlStr += '<div class="box_block order_opt_btm">';
						htmlStr += '<ul>';
						htmlStr += '<li class="text-center">';
						//htmlStr += '<button type="button" data-theme="b" class="yellow_btn" onClick=window.location.href="#ldhOrderlist">查看订单</button>';
						htmlStr += '<button type="button" data-theme="b" class="yellow_btn" onClick=window.location.href="'+ctx+'/h5/orders.shtml">查看订单</button>';
						htmlStr += '</li>';
						htmlStr += '</ul>';
						htmlStr += '</div>';
						
					}			
				}
				
				if(data["paymentId"]=='2'){
					//在线支付
					for(var i=0;i<data["orderInfos"].length;i++){
						
						htmlStr += '<div class="row">';
						htmlStr += '<ul>';
						htmlStr += '<li>';
						htmlStr += '<p class="order_success">订单提交成功，请付款</p>';
						htmlStr += '</li>';
						htmlStr += '<li><span>订单编号：</span><span class="orderId">'+data["orderInfos"][i]["orderId"]+'</span></li>';
						htmlStr += '<li><span>店铺名称：</span><span class="shopName">'+data["orderInfos"][i]["shopName"]+'</span></li>';
						htmlStr += '<li><span>应付金额：</span><span class="amount">'+Number(data["orderInfos"][i]["amount"]).toFixed(2)+'元</span></li>';
						htmlStr += '</ul>';
						htmlStr += '</div>';
						htmlStr += '<div class="box_block order_opt_btm">';
						htmlStr += '<ul>';
						htmlStr += '<li class="text-center">';
						//htmlStr += '<button type="button" data-theme="b" class="main_btn" onclick=window.location.href="?orderId='+data["orderInfos"][i]["orderId"]+'&orderAmount='+data["orderInfos"][i]["amount"]+'#ldhOnlinePay">付款</button><button type="button" data-theme="b" class="yellow_btn" onClick=window.location.href="#ldhOrderlist">查看订单</button>';
						htmlStr += '<button type="button" data-theme="b" class="main_btn" onclick=window.location.href="'+ctx+'/h5/onlinePay/'+data["orderInfos"][i]["orderId"]+'/'+Number(data["orderInfos"][i]["amount"]).toFixed(2)+'.shtml">付款</button><button type="button" data-theme="b" class="yellow_btn" onClick=window.location.href="'+ctx+'/h5/orders.shtml">查看订单</button>';

						htmlStr += '</li>';
						htmlStr += '</ul>';
						htmlStr += '</div>';
						
					}		
				
				}
				
				
				
				base.showDiv("#ldhOrderSuccess");
				
				$("#ldhOrderSuccess .orderContent").html(htmlStr);
				
			}else{
				
				showTips(data.message);
			}
			
			clickable=true;
			base.cancelLoading();
		}))().start();
	
	};
	//获取随机数图片
	exports.refresh=function() {
		var obj=document.getElementById("imgCode");
	    obj.src = ctx+"/ImageServlet?" + Math.random();
	};

});

